package com.rjwh.dingdong.client.activity.webbrowser;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.aishua.lib.utils.AsStrUtils;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.UrlUtil;
import com.rjwh.dingdong.client.view.BaseWebView;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

/**
 * web界面
 *
 * @author 王博扬
 * @ClassName WebActivity
 * @Description TODO(这里用一句话描述这个类的作用)
 * @date 2015-9-15 下午5:27:34
 * @history 1.YYYY-MM-DD author: description:
 */
public class WebActivity extends BaseActivity {
    private static final String TAG = WebActivity.class.getSimpleName();
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.webview)
    BaseWebView webView;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.webview_progressbar)
    ProgressBar webviewProgressbar;
    private String url;
    private ValueCallback<Uri> mUM;
    private ValueCallback<Uri[]> mUMA;
    private final static int FCR = 1;
    private String currentPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_layout);
        ButterKnife.bind(this);
        parseIntent();
        initToolbarHelper();
        setWebView();
    }

    public static void startActivity(Context context, String url) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            url = intent.getStringExtra("url");
        }
    }

    private void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();// 返回上一页面
                } else {
                    WebActivity.this.finish();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.menu_webview, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_webview:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("deprecation")
    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    public void setWebView() {
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtil.d("HTML", "url:" + url);
                // 处理自定义scheme
                if (url.startsWith("http")) {
                    view.loadUrl(url);
                } else if (url.contains("tiandilixin")) {
                    LogUtil.d("HTML", "handelUrl" + url);
                    UrlUtil.handelUrl(WebActivity.this, url, true);
                } else {
                    try {
                        final Intent intent = new Intent(Intent.ACTION_VIEW,
                                Uri.parse(url));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                    } catch (Exception e) {
                        // 防止没有安装的情况
                        e.printStackTrace();
                    }
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                dismissErrorLayout();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                LogUtil.e("WebActivity", errorCode + " ;" + description);
                showErrorLayout();
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView webView, int i) {
                if (i == 100) {
                    webviewProgressbar.setVisibility(GONE);
                } else {
                    if (webviewProgressbar.getVisibility() == GONE) {
                        webviewProgressbar.setVisibility(VISIBLE);
                        webviewProgressbar.setProgress(i);
                    }
                }
                super.onProgressChanged(webView, i);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                // TODO Auto-generated method stub
                super.onReceivedTitle(view, title);
                if (getSupportActionBar() != null && !AsStrUtils.isEmpty(title)) {
                    getSupportActionBar().setTitle(title);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                return super.onJsAlert(view, url, message, result);
            }

            //For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
            }

            // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FCR);
            }

            //For Android 4.1+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUM = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
            }

            //For Android 5.0+
            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    FileChooserParams fileChooserParams) {
                if (mUMA != null) {
                    mUMA.onReceiveValue(null);
                }
                mUMA = filePathCallback;
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", photoFile);
                        if (photoFile != null) {
                            currentPath = photoFile.getPath();
                            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                        } else {
                            takePictureIntent = null;
                        }
                    } catch (IOException ex) {
                        LogUtil.e(TAG, "Image file creation failed", ex);
                    }
                }
                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("image/*");
                Intent[] intentArray;
                if (takePictureIntent != null) {
                    intentArray = new Intent[]{takePictureIntent};
                } else {
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
//                chooserIntent.putExtra(Intent.EXTRA_TITLE, "选择图片");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                startActivityForResult(chooserIntent, FCR);
                return true;
            }
        });
        if (url != null) {
            LogUtil.d("HTML", "url:" + url);
//            url = "http://192.168.11.29:86/BeautifulTeacher.aspx";
            webView.loadUrl(url);
        }
        dismissErrorLayout();
    }

    // Create an image file
    private File createImageFile() throws IOException {
        File storageDir = new File(FileUtils.getTempImageStorageDirectory() + System
                .currentTimeMillis() + ".png");
        LogUtil.d(TAG, "storageDir:" + storageDir);
        return storageDir;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (Build.VERSION.SDK_INT >= 21) {
            Uri[] results = null;
            //Check if response is positive
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == FCR) {
                    if (null == mUMA) {
                        return;
                    }
                    if (intent == null) {
                        //Capture Photo if no image available
                        LogUtil.d(TAG, "Capture Photo");
                        if (currentPath != null) {
                            File file = new File(currentPath);
                            Uri localUri = Uri.fromFile(file);
                            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                            sendBroadcast(localIntent);
                            results = new Uri[]{localUri};
                        }
                    } else {
                        String dataString = intent.getDataString();
                        if (dataString != null) {
                            results = new Uri[]{Uri.parse(dataString)};
                        }
                    }
                }
                LogUtil.d(TAG, "results:" + results);
                mUMA.onReceiveValue(results);
                mUMA = null;
            } else {
                //取消操作传null,否则不能再次点击
                LogUtil.d(TAG, "SDK_INT >= 21 requestCode ! RESULT_OK");
                if (null == mUMA) {
                    return;
                }
                mUMA.onReceiveValue(null);
                mUMA = null;
            }
        } else {
            if (resultCode == Activity.RESULT_OK) {
                LogUtil.d(TAG, "SDK_INT < 21 requestCode RESULT_OK");
                if (requestCode == FCR) {
                    if (null == mUM) return;
                    Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                    LogUtil.d(TAG, "SDK_INT < 21 result:" + result);
                    mUM.onReceiveValue(result);
                    mUM = null;
                }
            } else {
                //取消操作传null,否则不能再次点击
                LogUtil.d(TAG, "SDK_INT < 21 requestCode ! RESULT_OK");
                if (null == mUM) return;
                mUM.onReceiveValue(null);
                mUM = null;
            }
        }

    }

    private void showErrorLayout() {
        if (errorLayout != null) {
            errorLayout.setVisibility(VISIBLE);
        }
    }

    private void dismissErrorLayout() {
        if (errorLayout != null) {
            errorLayout.setVisibility(GONE);
        }
    }

    private void showLoadingLayout() {
//        if (loadingLayout != null) {
//            loadingLayout.setVisibility(VISIBLE);
//        }
    }

    private void dismissLoadingLayout() {
//        if (loadingLayout != null) {
//            loadingLayout.setVisibility(GONE);
//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (webView.canGoBack()) {
                webView.goBack();// 返回上一页面
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        if (webView != null) {
//            webView.clearCache(true);
//            webView.clearHistory();
            webView.setVisibility(GONE);
            webView.removeAllViews();
            webView.destroy();
        }
        super.onDestroy();
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) {
            webView.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) {
            webView.onResume();
        }

    }

    @OnClick(R.id.btn_refresh)
    public void onClick() {
        webView.reload();
        dismissErrorLayout();
    }
}
